package com.swjd.config;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@EnableWebSecurity //开启security安全的支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    //重写方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置密码编码器
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        //内存身份认证
//        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> authenticationManagerBuilderInMemoryUserDetailsManagerConfigurer = auth.inMemoryAuthentication().passwordEncoder(bCryptPasswordEncoder);
//        //设置用户名 密码 权限
//        authenticationManagerBuilderInMemoryUserDetailsManagerConfigurer.withUser("shitou").password(bCryptPasswordEncoder.encode("123")).roles("comment");
//        authenticationManagerBuilderInMemoryUserDetailsManagerConfigurer.withUser("李四").password(bCryptPasswordEncoder.encode("321")).roles("vip");
        //使用jdbc进行身份认证
        JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> authenticationManagerBuilderJdbcUserDetailsManagerConfigurer = auth.jdbcAuthentication().passwordEncoder(bCryptPasswordEncoder);
        authenticationManagerBuilderJdbcUserDetailsManagerConfigurer.dataSource(dataSource);
        //用户名 密码
        authenticationManagerBuilderJdbcUserDetailsManagerConfigurer.usersByUsernameQuery("SELECT username,PASSWORD,valid FROM t_customer WHERE username = ?");
       //用户级别
        authenticationManagerBuilderJdbcUserDetailsManagerConfigurer.authoritiesByUsernameQuery("SELECT a.authority,c.username FROM t_customer c,t_authority a,t_customer_authority ta WHERE c.id = ta.customer_id AND a.id = ta.authority_id AND c.username = ?");


    }
}
